package com.example.demo1.interceptor;

import com.example.demo1.util.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
@Slf4j
public class Interceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求URL
        String url = request.getRequestURI();

        // 登录和注册接口放行
        if (url.contains("/login") || url.contains("/register")) {
            return true;
        }

        // 获取token
        String token = request.getHeader(JWTUtil.HEADER);

        // 检查token是否为空
        if (token == null || token.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("无权访问");
            return false;
        }

        // 验证token是否过期
        if (JWTUtil.isTokenExpired(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("无权访问");
            return false;
        }

        // 获取用户名和角色
        String username = JWTUtil.getUsernameFromToken(token);
        String role = JWTUtil.getRoleFromToken(token);

        // 将用户信息和角色存入request属性
        request.setAttribute("username", username);
        request.setAttribute("role", role);

        log.info("Token验证成功，用户：{}，角色：{}", username, role);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 后处理方法，可以在这里进行一些额外的处理
        log.debug("PostHandle method is called");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后的处理
        String url = request.getRequestURI();
        log.info("请求完成，URL：{}，状态码：{}", url, response.getStatus());

        // 可以在这里进行一些清理工作，比如清除线程局部变量
        if (ex != null) {
            log.error("请求处理发生异常", ex);
        }
    }
}